import CONSTANT from '../stores/constant.js';
const errorCode = {
	'401': '认证失败，无法访问系统资源',
	'403': '当前操作没有权限',
	'404': '访问资源不存在',
	'default': '系统未知错误，请反馈给管理员'
}
const fetch = (url, body = {}, method = 'post', loading = false) => {
	let baseUrl = 'http://www.zhugezg.com/xq/xqApp/'
	let hideLoading = loading || false;
	let header = {
		'Content-Type': 'application/json',
	};
	const token = uni.getStorageSync('token');
	const userInfo = uni.getStorageSync(CONSTANT.USER_KEY)
	if (token) {
		body.token = token
	}
	if (userInfo) {
		body.u = userInfo.phone
	}
	url = baseUrl + url
	method = method.toUpperCase();
	//用户交互:加载圈
	if (!hideLoading) {
		uni.showLoading({
			title: '加载中...'
		});
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			method,
			header,
			data: body,
		}).then(res => {
			const resdata = res[1]
			const code = resdata.data.code || 1;
			// 获取错误信息
			const msg = resdata.data.message
			if (!hideLoading) {
				uni.hideLoading();
			}
			if (code != 1) {
				responseCode(code, msg)
			}

			if (code == 1) {
				resolve(resdata.data.data)
			}
		}).catch(err => {
			
			const code = 400;
			// 获取错误信息
			const msg = errorCode[code] || errorCode['default']
			if (!hideLoading) {
				uni.hideLoading();
			}
			responseCode(code, msg)
			reject(err)
		})
	})
}

const responseCode = (code, msg) => {
	
	if (code === 401) {
		return uni.navigateTo({
			url: '/pages/login/login.vue'
		})
	} else if (code === 500) {
		return uni.showModal({
			content: msg
		});

	} else if (code === 10000) {
		return uni.showModal({
			content: msg,
			success: function(res) {
				if (res.confirm) {
					uni.navigateBack({
						delta: 1
					})
				} else if (res.cancel) {
					uni.navigateBack({
						delta: 1
					})
				}
			}
		});
	} else if(code === -1) {
		return uni.showModal({
			content: msg || '接口错误'
		});
	} else if(code === -2) {
		uni.removeStorageSync('user')
		uni.removeStorageSync('token')
		return uni.reLaunch({
			url: '/pages/login/login'
		})
	}
	if (code !== 200) {
		return uni.showModal({
			content: msg
		});
	}
}


export default fetch
